package consule

import (
	"BaseSrv/common/global"
	"fmt"

	"github.com/hashicorp/consul/api"
)

type Registry struct {
	Host string
	Port int
}

type RegistryClient interface {
	Register(address string, port int, name string, tags []string, id string) error
	DeRegister(serviceId string) error
	GetService() map[string]*api.AgentService
	FilterService(serviceName string) map[string]*api.AgentService
}

func NewRegistryClient(host string, port int) RegistryClient {
	return &Registry{
		Host: host,
		Port: port,
	}
}

// 注册服务
func (r *Registry) Register(address string, port int, name string, tags []string, id string) error {
	//生成对应的检查对象
	//check := &api.AgentServiceCheck{
	//	HTTP:                           fmt.Sprintf("http://%s:%d/health", address, port),
	//	Timeout:                        "5s",
	//	Interval:                       "5s",
	//	DeregisterCriticalServiceAfter: "10s",
	//}

	//生成注册对象
	registration := new(api.AgentServiceRegistration)
	registration.Name = name
	registration.ID = id
	registration.Port = port
	registration.Tags = tags
	registration.Address = address
	//registration.Check = check

	err := global.ConsuleClient.Agent().ServiceRegister(registration)
	if err != nil {
		panic(err)
	}
	return nil
}

// 注销服务
func (r *Registry) DeRegister(serviceId string) error {
	err := global.ConsuleClient.Agent().ServiceDeregister(serviceId)
	return err
}

// 获取所有服务
func (r *Registry) GetService() map[string]*api.AgentService {
	result, err := global.ConsuleClient.Agent().Services()
	if err != nil {
		panic(err)
	}
	return result
}

// 过滤服务
func (r *Registry) FilterService(serviceName string) map[string]*api.AgentService {
	result, err := global.ConsuleClient.Agent().ServicesWithFilter(fmt.Sprintf(`Service == "%s"`, serviceName))
	if err != nil {
		panic(err)
	}
	return result
}
